import React, { useRef, useState } from 'react'
import { SchemaForm, Item, Submit, Reset, Layout, SchemaType } from '@amazebird/antd-schema-form'

const schema: SchemaType = {
  user: {
    label: '用户名',
    component: 'Input',
    required: true,
    rules: [{
      max: 5,
      message: '用户名最长不超过5个字符'
    }]
  },
  nickName: {
    label: '昵称',
    component: 'Input',
    placeholder: '请输入用户名',
    required: [true, '请输入用户名'],
    max: [10, '最多只能输入10个字符']
  },
  password: {
    label: '密码',
    component: 'Input',
    placeholder: '请输入密码',
    required: true,
    min: 6,
    rules: [{
      max: 10,
      message: '密码最长不超过10个字符'
    }, {
      pattern: /^[a-zA-Z_]{1,}$/,
      message: '仅支持输入英文、下划线'
    }]
  }
}

function RuleDemo() {
  const [imageUrl, setImageUrl] = useState()
  const formRef = useRef(null)

  function onFinish(data) {
    console.info('提交成功', data)
  }

  function onError(data) {
    console.error('发生错误', data)
  }

  return (
    <>
      <div ref={formRef}>
        <SchemaForm schema={schema}>
          <Item field="user" />
          <Item field="nickName" />
          <Item field="password" />
          <Layout align="left" offset={8}>
            <Submit onFinish={onFinish} onError={onError} />
            <Reset />
          </Layout>
        </SchemaForm>
      </div>

      {imageUrl && <img src={imageUrl} />}
    </>
  )
}

export default RuleDemo
